package com.zzyl.common.ai;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class QianfanChatService {

    @Autowired
    private AiProperties aiProperties;

    @Autowired
    private RestTemplate restTemplate;

    private final ObjectMapper objectMapper;

    public QianfanChatService(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    private String chatCompletion(String model, List<Map<String, String>> messages) {
        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", model);
        requestBody.put("messages", messages);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(aiProperties.getAuthToken());

        // 创建HTTP实体
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        try {
            ResponseEntity<String> response = restTemplate.exchange(
                    aiProperties.getBaseUrl(),
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );

            return response.getBody();

        } catch (HttpClientErrorException e) {
            throw new RuntimeException("API request failed: " + e.getMessage(), e);
        }
    }

    /**
     * 从API响应中提取content内容 - 使用Jackson JSON工具类
     *
     * @param jsonResponse API返回的JSON字符串
     * @return assistant回复的内容
     */
    private String extractContent(String jsonResponse) {
        try {
            // 使用Jackson ObjectMapper解析JSON
            JsonNode rootNode = objectMapper.readTree(jsonResponse);

            // 通过路径访问content字段
            JsonNode contentNode = rootNode
                    .path("choices")
                    .get(0)
                    .path("message")
                    .path("content");

            // 检查节点是否存在并返回文本值
            if (contentNode != null && !contentNode.isMissingNode()) {
                return contentNode.asText();
            }

            return null;
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse JSON response: " + e.getMessage(), e);
        }
    }

    /**
     * 调用此方法返回问AI的到结果
     *
     * @param prompt 用户输入的提示词
     * @return AI回复的内容
     */
    public String getReturnContent(String prompt) {
        // 直接使用当前实例的方法，而不是创建新实例
        // 构建消息列表
        List<Map<String, String>> messages = new ArrayList<>();

        Map<String, String> systemMessage = new HashMap<>();
        systemMessage.put("role", "system");
        systemMessage.put("content", "平台助手");
        messages.add(systemMessage);

        Map<String, String> userMessage = new HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", prompt);
        messages.add(userMessage);

        // 调用API - 使用当前实例(this)
        try {
            String result = this.chatCompletion("ernie-4.0-turbo-8k", messages);
            // 提取content内容
            String content = this.extractContent(result);
//            System.out.println("Extracted Content: " + content);
            return content;
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
}
